package com.zhichan.mslocator

import com.zhichan.mslocator.helper.LocatorHelper

import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result

/** MslocatorPlugin */
class MslocatorPlugin : FlutterPlugin, MethodCallHandler, ActivityAware {
    /// The MethodChannel that will the communication between Flutter and native Android
    ///
    /// This local reference serves to register the plugin with the Flutter Engine and unregister it
    /// when the Flutter Engine is detached from the Activity
    private lateinit var channel: MethodChannel

    private var locatorHelper: LocatorHelper? = null

    override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        locatorHelper = LocatorHelper()
        channel = MethodChannel(flutterPluginBinding.binaryMessenger, "mslocator")
        channel.setMethodCallHandler(this)
    }

    override fun onMethodCall(call: MethodCall, result: Result) {
        when (call.method) {
            "getPlatformVersion" -> result.success("Android ${android.os.Build.VERSION.RELEASE}")
            "getLastKnownPosition" -> locatorHelper?.getLastKnownPosition(result)
            "checkLocationService" -> locatorHelper?.checkLocationService(result)
            else -> result.notImplemented()
        }
    }

    override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        channel.setMethodCallHandler(null)
        locatorHelper?.setActivity(null)
        locatorHelper = null
    }

    override fun onAttachedToActivity(binding: ActivityPluginBinding) {
        locatorHelper?.setActivity(binding.activity)
    }

    override fun onDetachedFromActivityForConfigChanges() {
        locatorHelper?.setActivity(null)
    }

    override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
        locatorHelper?.setActivity(binding.activity)
    }

    override fun onDetachedFromActivity() {
        locatorHelper?.setActivity(null)
    }
}
